<?php

class Magestore_Mageconnector_IndexController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {
        try {
            $action = $this->getRequest()->get('action');
            $storeCode = $this->getRequest()->get('view');
            $baseUrl = $this->getParamBaseUrl();

            switch ($action) {
                case 'version':
                    $this->getCurrentVersion();
                    break;
                case 'view':
                    $this->storeView($baseUrl);
                    break;
                case 'category':
                    $this->category($baseUrl, $storeCode);
                    break;
                case 'checkout':
                    $this->checkout($baseUrl, $storeCode);
                    break;
                
                case 'addToCart':
                    $this->addToCart($baseUrl, $storeCode);
                    break;
                case 'refreshCart':
                    $this->refreshCart($baseUrl, $storeCode);
                    break;
                case 'updateCart':
                    $this->updateCart($baseUrl, $storeCode);
                    break;
                case 'cartApplyCoupon':
                    $this->cartApplyCoupon($baseUrl, $storeCode);
                    break;
                case 'cartCancelCoupon':
                    $this->cartCancelCoupon($baseUrl, $storeCode);
                    break;
                case 'deleteCartItem':
                    $this->deleteCartItem($baseUrl, $storeCode);
                    break;
                case 'cart':
                    $this->cartData($baseUrl, $storeCode);
                    break;
                
                case 'debug':
                    $this->debug();
                    break;
                default:
                    $this->product($baseUrl, $storeCode);
            }
        } catch (Magestore_Mageconnector_Exception $e) {
            $xml = '<?xml version="1.0"?><exception><message><![CDATA[' . $e->getMessage() . ']]></message></exception>';
            $response = $this->getResponse();
            $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                    ->setBody($xml);
        }
    }

    private function cartData($baseUrl, $storeCode) {
        $output = Mage::getModel('mageconnector/cart')
                        ->getCartData(
                                $baseUrl, $storeCode
        );

        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                ->setBody($output);
    }

    private function getParamBaseUrl() {
        $baseUrl = $this->getRequest()->get('baseUrl');
        $baseUrl = split('index.php', urldecode($baseUrl));
        if (count($baseUrl)) {
            $baseUrl = rtrim($baseUrl[0], '/');
        }
        return $baseUrl . '/';
    }

    /**
     * Get Current Version of this module
     * 
     */
    private function getCurrentVersion() {
        $version = new Magestore_Mageconnector_Model_Information();
        echo $version->getVersion();
    }

    /**
     * Get list store view by base url
     *
     * @param string $baseUrl
     */
    private function storeView($baseUrl) {
        $output = Mage::helper('mageconnector')
                        ->getListStoreViewCodesByStoreBaseUrl(
                                $baseUrl
        );

        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                ->setBody($output);
    }

    private function category($baseUrl, $storeCode) {
        $output = Mage::getModel('mageconnector/category')
                        ->exportXML($baseUrl, $storeCode);

        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                ->setBody($output);
    }

    private function checkout($baseUrl, $storeCode) {
        $checkoutUrl = Mage::getModel('mageconnector/cart')->getCheckoutPage($baseUrl, $storeCode);
        header("Location: $checkoutUrl");
        die();
    }

    private function addCartDataToUrl(&$url, $baseUrl, $storeCode) {
        $cartData = Mage::getModel('mageconnector/cart')
                        ->exportXML($baseUrl, $storeCode);

        $cartData = urlencode($cartData);
        $url .= "&cart=$cartData";
    }

    private function addToCart($baseUrl, $storeCode) {
        $result = Mage::getModel('mageconnector/cart')
                        ->addToCart($baseUrl, $storeCode);

        $url = $_REQUEST['url'];
        $url = urldecode($url);
        if ($result) {
            $url .= "&addToCart=success";
        } else {
            $url .= "&addToCart=unsuccess";
        }
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function refreshCart($baseUrl, $storeCode) {
        $url = $_REQUEST['url'];
        $url = urldecode($url);
        $url .= "&refreshCart=success";
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function cartApplyCoupon($baseUrl, $storeCode) {
        $result = Mage::getModel('mageconnector/cart')
                        ->applyCoupon($baseUrl, $storeCode);

        $url = $_REQUEST['couponUrl'];
        $url = urldecode($url);
        if ($result) {
            $url .= "&applyCoupon=success&couponCode=" . $_REQUEST['coupon_code'];
        } else {
            $url .= "&applyCoupon=unsuccess&couponCode=" . $_REQUEST['coupon_code'];
        }
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function cartCancelCoupon($baseUrl, $storeCode) {
        $result = Mage::getModel('mageconnector/cart')
                        ->cancelCoupon($baseUrl, $storeCode);

        $url = $_REQUEST['couponUrl'];
        $url = urldecode($url);
        if ($result) {
            $url .= "&cancelCoupon=success";
        } else {
            $url .= "&cancelCoupon=unsuccess";
        }
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function updateCart($baseUrl, $storeCode) {
        $result = Mage::getModel('mageconnector/cart')
                        ->updateCart($baseUrl, $storeCode);

        $url = $_REQUEST['url'];
        $url = urldecode($url);
        if ($result) {
            $url .= "&updateCart=success";
        } else {
            $url .= "&updateCart=unsuccess";
        }
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function deleteCartItem($baseUrl, $storeCode) {
        $result = Mage::getModel('mageconnector/cart')
                        ->deleteCartItem($baseUrl, $storeCode);

        $url = $_REQUEST['url'];
        $url = urldecode($url);
        if ($result) {
            $url .= "&deleteCartItem=success";
        } else {
            $url .= "&deleteCartItem=unsuccess";
        }
        $this->addCartDataToUrl($url, $baseUrl, $storeCode);
        header("Location: $url");
    }

    private function product($baseUrl, $storeCode) {
        $keyword = $this->getRequest()->get('keyword');
        $category = $this->getRequest()->get('category');

        if ($keyword != '') {
            $output = $this->productSearch($baseUrl, $storeCode, $keyword, $category, $baseUrl, $storeCode);
        } else {
            $urlKey = $this->getRequest()->get('url_key');
            if ($urlKey != '') {
                $output = $this->productDetail($urlKey, $baseUrl, $storeCode);
            } else {
                if ($category != '') {
                    $output = $this->productCategory($category, $baseUrl, $storeCode);
                } else {
                    $output = $this->allProducts($baseUrl, $storeCode);
                }
            }
        }

        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                ->setBody($output);
    }

    private function productCategory($category, $baseUrl, $storeCode) {
        $currentPage = $this->getRequest()->get('page');
        $pageSize = $this->getRequest()->get('pageSize');
        $orderBy = $this->getRequest()->get('orderBy');
        $typeOrder = $this->getRequest()->get('typeOrder');
        $showProductsInSubCategories = $this->getRequest()->get('showProductsInSubCategories');

        return Mage::getModel('mageconnector/product')
                ->getProductListByCategory($category, $baseUrl, $storeCode, $currentPage, $pageSize, $orderBy, $typeOrder, $showProductsInSubCategories);
    }

    private function productSearch($baseUrl, $storeCode, $keyword, $category) {
        $currentPage = $this->getRequest()->get('page');
        $pageSize = $this->getRequest()->get('pageSize');
        $orderBy = $this->getRequest()->get('orderBy');
        $typeOrder = $this->getRequest()->get('typeOrder');
        $showProductsInSubCategories = $this->getRequest()->get('showProductsInSubCategories');

        return Mage::getModel('mageconnector/product')
                ->searchProduct($baseUrl, $storeCode, $keyword, $category, $currentPage, $pageSize, $orderBy, $typeOrder, $showProductsInSubCategories);
    }

    private function productDetail($productUrlKey, $baseUrl, $storeCode) {
        return Mage::getModel('mageconnector/product')
                ->getProductDetail($productUrlKey, $baseUrl, $storeCode);
    }

    private function allProducts($baseUrl, $storeCode) {
        $currentPage = $this->getRequest()->get('page');
        $pageSize = $this->getRequest()->get('pageSize');
        $orderBy = $this->getRequest()->get('orderBy');
        $typeOrder = $this->getRequest()->get('typeOrder');
        
        return Mage::getModel('mageconnector/product')
                ->searchProduct($baseUrl, $storeCode, '', '', $currentPage, $pageSize, $orderBy, $typeOrder);
    }

    public function debug() {
        $products = Mage::getModel('catalog/product')->getCollection()
                        ->addAttributeToSelect('name')
                        ->addStoreFilter(1)
                        ->addAttributeToFilter(array(
                            array(
                                'attribute' => 'visibility',
                                'in' => array(3, 4)
                            )
                        ))
                        ->addFieldToFilter("status", 1);

        $xml = '<?xml version="1.0"?><products>';

        $i = 0;
        foreach ($products as $p) {
            $product = Mage::getModel('catalog/product')
                            ->setStoreId(1)
                            ->load($p->getId());
            $xml .= '<product order="#' . ++$i . '">'
                    . '<id>' . $product->getId() . '</id>'
                    . '<name><![CDATA[' . $product->getName() . ']]></name>'
                    . '<price><![CDATA[' . Mage::helper('core')
                            ->currency(Mage::helper('tax')
                                    ->getPrice(
                                            $product,
                                            $product->getFinalPrice()
                                    )
                                    , true, false) . ']]></price>'
                    . '<description><![CDATA[' . $product->getShortDescription() . ']]></description>'
                    . '</product>';
        }

        $xml .= '</products>';
        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml; charset=utf-8')
                ->setBody($xml);
    }

}